import React, {PureComponent} from 'react';
import PropTypes from 'prop-types';
import {Row, Col, Form, Button, Divider, Table, message as msg, Modal} from 'antd';
import {PAGE, TABLE, PAGINATION_OPTIONS, FORM_OPTIONS} from '../constants';
import TextInput from 'Shared/components/TextInput';
import SelectAlert from '../common/SelectAlert';
import {computeSelectedRows} from './utils';
import {conventSorter, conventEnumValueToString} from '../utils';
import styles from './style.css';
import {salePackingQuery} from './api';
import Ellipsis from 'ant-design-pro/lib/Ellipsis';
import cloneDeep from 'lodash/cloneDeep';
import {packingType} from '../Enum';
const FormItem = Form.Item;
const MultiSelectAlert = SelectAlert.Multi;

class SalePackingListPanel extends PureComponent {
    state = {
        code: '',
        isFetching: false,
        data: {},
        message: '',
        pageIndex: PAGE.index,
        pageSize: PAGE.smallSize,
        currentCondition: {},
        selectedRowKeys: [],
        selectedRows: [],
    }
    
    handleTableChange = (pagination, filters, sorter) => {
        const oldCondition = {...this.state.currentCondition};
        if(pagination.current - 1 === oldCondition.pageIndex && pagination.pageSize === oldCondition.pageSize) {
            const sortOptions = conventSorter(sorter);
            const condition = Object.assign({}, oldCondition, sortOptions, {
                pageIndex: pagination.current - 1
            });
            this.onQuery(condition);
            this.setState({
                sortField: sortOptions.sortField,
                isDesc: sortOptions.isDesc
            });
        }
    }

    handleFilterPressEnter = (value, name) => {
        this.setState({[name]: value}, this.onClickSearchBtn);
    }

    onQuery = condition => {
        this.setState({isFetching: true});
        salePackingQuery(condition)
            .then(res => {
                if(res.ok)
                    this.setState({
                        isFetching: false,
                        message: '',
                        data: res.data,
                        currentCondition: condition
                    });
                else
                    this.setState({
                        isFetching: false,
                        data: [],
                        message: res.message
                    });
            });
    }

    onClickSearchBtn = () => {
        const condition = {
            code: this.state.data.code,
            dealerId: this.props.dealerId,
            brandId: this.props.brandId,
            pageIndex: PAGE.index,
            pageSize: this.state.pageSize,
            sortField: this.state.sortField,
            isDesc: this.state.isDesc
        };
        this.onQuery(condition);
    }

    onPageIndexChange = current => {
        const condition = {...this.state.currentCondition};
        condition.pageIndex = current - 1;
        this.onQuery(condition);
    }

    onPageSizeChange = (current, pageSize) => {
        const condition = {...this.state.currentCondition};
        condition.pageIndex = PAGE.index;
        condition.pageSize = pageSize;
        this.onQuery(condition);
        this.setState({
            pageSize
        });
    }

    onChange = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }

    onClickReset = () => {
        this.setState({
            code: '',
        });
    }

    onChangeRadio = (selectedRowKeys, selectedRows) => {
        this.setState({
            selectedRowKeys,
            selectedRows
        });
    }

    onCloseTag = () => {
        this.setState({
            selectedRowKeys: [],
            selectedRows: []
        });
    }

    onSubmit = () => {
        if(!this.state.selectedRows.length)
            return msg.warn(this.props.intl.formatMessage({
                id: 'salePackingListPanel.validate.title',
                defaultMessage: '请选择包装箱单'
            }));
        this.props.onSelect(this.state.selectedRows);
    }
    
    onSelectDealer = (condition = {}) => {
        this.setState(state => {
            const newData = cloneDeep(state.data);
            return {
                hasOperat: true,
                data: {
                    ...newData,
                    dealerId: condition.id,
                    dealerCode: condition.code,
                    dealerName: condition.name,
                }
            };
        });
    };
    render() {
        const {formatMessage} = this.props.intl;
        const {isFetching, data} = this.state;
        const {pageIndex, pageSize} = this.state.currentCondition;
        const columns = [
            {
                title: formatMessage({
                    id: 'salePackingListPanel.column.code',
                    defaultMessage: '包装箱单号'
                }),
                sorter: true,
                dataIndex: 'code',
            }, {
                title: formatMessage({
                    id: 'salePackingListPanel.column.dealerCode',
                    defaultMessage: '总代编号'
                }),
                dataIndex: 'dealerCode',
            }, {
                title: formatMessage({
                    id: 'salePackingListPanel.column.dealerName',
                    defaultMessage: '总代名称'
                }),
                dataIndex: 'dealerName',
            }, {
                title: formatMessage({
                    id: 'salePackingListPanel.column.palletCode',
                    defaultMessage: '托盘号'
                }),
                dataIndex: 'palletCode',
                sorter: true,
                render: text => <Ellipsis tooltip fullWidthRecognition length={25}>{text}</Ellipsis>
            }, {
                title: formatMessage({
                    id: 'salePackingListPanel.column.packingType',
                    defaultMessage: '包装类型'
                }),
                dataIndex: 'packingType',
                render: text => conventEnumValueToString(packingType, text)
            }, {
                title: formatMessage({
                    id: 'salePackingListPanel.column.container',
                    defaultMessage: '包装规格'
                }),
                dataIndex: 'container',
            }, {
                title: formatMessage({
                    id: 'salePackingListPanel.column.length',
                    defaultMessage: '长度'
                }),
                dataIndex: 'length',
            }, {
                title: formatMessage({
                    id: 'salePackingListPanel.column.width',
                    defaultMessage: '宽度'
                }),
                dataIndex: 'width',
            }, {
                title: formatMessage({
                    id: 'salePackingListPanel.column.height',
                    defaultMessage: '高度'
                }),
                dataIndex: 'height',
            }, {
                title: formatMessage({
                    id: 'salePackingListPanel.column.volume',
                    defaultMessage: '体积'
                }),
                dataIndex: 'volume',
            }, {
                title: formatMessage({
                    id: 'salePackingListPanel.column.netWeight',
                    defaultMessage: '净重'
                }),
                dataIndex: 'netWeight',
            }, {
                title: formatMessage({
                    id: 'salePackingListPanel.column.grossWeight',
                    defaultMessage: '毛重'
                }),
                dataIndex: 'grossWeight',
            },
        ];
            
        const pagination = {
            total: data.totalElements,
            current: pageIndex + 1,
            pageSize,
            onShowSizeChange: this.onPageSizeChange,
            onChange: this.onPageIndexChange,
            ...PAGINATION_OPTIONS
        };
        const rowSelection = {
            selectedRowKeys: this.state.selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                const rows = computeSelectedRows(this.state.selectedRowKeys, this.state.selectedRows, selectedRowKeys, selectedRows);
                this.setState({
                    selectedRowKeys,
                    selectedRows: rows
                });
            }
        };
        return (
            <Modal
                title={formatMessage({
                    id: 'salePackingListPanel.show.query',
                    defaultMessage: '整车包装箱单查询'
                })}
                width="60%"
                maskClosable={false}
                footer={null}
                destroyOnClose={true}
                wrapClassName={styles.dataSelectModal}
                visible={true}
                onCancel={this.props.onCancel}>
                <Row className="form-standard">
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem
                            label={this.props.intl.formatMessage({
                                id: 'salePackingListPanel.form.code',
                                defaultMessage: '包装箱单号'
                            })}
                            {...FORM_OPTIONS.item}>
                            <TextInput
                                name="code"
                                value={this.state.code}
                                onPressEnter={this.handleFilterPressEnter}
                                onBlur={this.onChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col} className={styles['inline-button']}>
                        <Button
                            type="primary"
                            loading={isFetching}
                            onClick={this.onClickSearchBtn}>
                            {formatMessage({
                                id: 'salePackingListPanel.btn.query',
                                defaultMessage: '查询'
                            })}
                        </Button>
                        <Button key="clear" onClick={this.onClickReset}>{formatMessage({
                            id: 'salePackingListPanel.btn.reset',
                            defaultMessage: '重置'
                        })}</Button>
                    </Col>
                </Row>
                <Divider className={styles.divider}/>
                <MultiSelectAlert data={this.state.selectedRows}
                    onConfirm={this.onSubmit}
                    onDelete={this.onCloseTag}
                    onDeleteAll={this.onCloseTag}/>
                <Table
                    className="white-space-nowrap"
                    rowKey="id"
                    dataSource={data.content}
                    rowClassName={styles.tableCursor}
                    columns={columns}
                    loading={isFetching}
                    pagination={pagination}
                    onChange={this.handleTableChange}
                    rowSelection={rowSelection}
                    {...TABLE}/>
            </Modal >
        );
    }
}

SalePackingListPanel.propTypes = {
    initEnum: PropTypes.object.isRequired,
    onSelect: PropTypes.func.isRequired,
    brandId: PropTypes.string,
    dealerId: PropTypes.string,
    intl: PropTypes.object,
    onCancel: PropTypes.func,
};
import {injectIntl} from './intl';
export default injectIntl(SalePackingListPanel);
